import {createRouter,createWebHistory} from 'vue-router'
import { useTokenStore } from '@/stores/token'
//导入组件
import LoginVue from '@/views/user/Login.vue'
import Register from '@/views/user/Register.vue'

//定义路由关系
const routes = [
    {path:'/',redirect:'/login'},
    {path:'/login',component:LoginVue, meta: { title: '用户登录', guest: true }},
    {path:'/register',component:Register, meta: { title: '注册', guest: true }},
    // 用户相关路由
    {
        path: '/student',
        component: () => import('@/views/user/UserLayout.vue'),
        meta: { requiresAuth: true },
        children: [
            {path: 'home', component: () => import('@/views/user/Home.vue'), meta: { title: '用户首页' }},
        ]
    },
    // 管理员相关路由
    {
        path:'/admin',
        component:() => import('@/views/admin/AdminLayout.vue'),
        meta: { requiresAdmin: true },
        children: [
          {path:'users',component:() => import('@/views/admin/Users.vue'), meta: { title: '用户管理' }},
          {path:'dashboard',component:() => import('@/views/admin/Dashboard.vue'), meta: { title: '主页' }},
        ]
    },
    // 404页面
    {path:'/:pathMatch(.*)*',component:() => import('@/views/NotFound.vue'), meta: { title: '404 Not Found' }}
]

//创建路由器
const router = createRouter({
    routes:routes,
    history:createWebHistory()
})


// 全局路由守卫
router.beforeEach((to, from, next) => {
    const tokenStore = useTokenStore()
    const title = to.meta.title
    if (title) {
        document.title = title
    }

    // 处理需要登录的路由
    if (to.meta.requiresAuth) {
        if (!tokenStore.token) {
            next({ path: '/login' })
            return
        }
    }

    // 处理需要管理员权限的路由
    if (to.meta.requiresAdmin) {
        if (!tokenStore.token) {
            next({ path: '/login' })
            return
        }
         

        if (tokenStore.studentInfo.role !== 'admin') {
            next({ path: '/student/home' })
            return
            next({ path: '/login' })
            return
        }
    }

    // 已登录用户访问登录页面时重定向到首页
    if (to.meta.guest && tokenStore.token) {
        if (tokenStore.studentInfo.role === 'admin') {
            next({ path: '/admin/dashboard' })
        } else {
            next({ path: '/student/home' })
        }
        return
    }

    next()
})

//导出路由
export default router